import axios from "axios";
import store from '../store/index'
import router from "../router";

// console.log(import.meta.env)

const request = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL
});

request.interceptors.request.use(
    (config) => {
        const token = store.state.token
        if (token) { // 判断是否存在token，如果存在的话，则每个http header都加上token
            config.headers['ACCESS-TOKEN'] = token //请求头加上token
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

request.interceptors.response.use(
    (response) => {
        if (response.data.code == 3) {
            sessionStorage.setItem("token", '');
            store.commit('settoken', '')
            console.log('用户未登录')
            router.push({ path: '/login' })
            return response.data;
        } else if (response.status == 200 && response.data.code == 1) {
            return response.data;
        } else {
            return response.data;
        }
    },
    (error) => {
        return Promise.reject(error);
    }
);

export default request